package cn.orange.ch07_binarytree;

import cn.orange.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * LC144.二叉树的前序遍历
 */
public class LC144 {
    public List<Integer> preorderTraversalD(TreeNode root) { //迭代写法
        List<Integer> res = new ArrayList<>();
        LinkedList<TreeNode> stack = new LinkedList<>();
        TreeNode curr = root;
        TreeNode pop = null;
        while (curr != null || !stack.isEmpty()) {
            if (curr != null) {
                res.add(curr.val);
                stack.push(curr);
                curr = curr.left;
            } else { //curr == null意味着向左处理到头
                TreeNode peek = stack.peek();
                if (peek.right == null || peek.right == pop) { //这两种情况表示栈顶节点的左右子树都处理完成
                    pop = stack.pop();
                } else {
                    curr = peek.right;
                }
            }
        }
        return res;
    }
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        preTraversal(root, list);
        return list;
    }
    private void preTraversal(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }
        list.add(root.val);
        preTraversal(root.left, list);
        preTraversal(root.right, list);
    }

    public static void main(String[] args) {
        LC144 alg = new LC144();
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        System.out.println(alg.preorderTraversalD(root));
    }
}
